#include<stdio.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>

#define NUM 1000
#define COMMANDCONUT 64
char LineCommand[NUM]; 
char *CommandExec[COMMANDCONUT];
// 真正的shell就是用子进程去执行各种命令


int main()
{
   while(1)
   {
      printf("[%s@云服务器]:",getenv("USER"));
      fflush(stdout);
     // Line 表示缓冲区
      char *s = fgets(LineCommand,sizeof(LineCommand)-1,stdin);  
      assert(s!=NULL);
      // 这里要删一个换行符
      (void)s; 
      LineCommand[strlen(LineCommand)-1] =  0; 

      printf("Command:%s\n",LineCommand);

      // 开始分割s , 用strtok
      CommandExec[0] = strtok(LineCommand," ");
      int i = 1;
      // 有点妙的这一行，先分割写入CommandExec ，最后判读CommandExec[i]是否为空
      while(CommandExec[i++] = strtok(NULL," ") );

      //内嵌命令cd,本命令子进程调用无效
      if(strcmp(CommandExec[0], "cd") == 0 )
      {
         if(strcmp(CommandExec[1] , "..") == 0)
         {
             chdir(CommandExec[1]);
             continue;
         }
      }


      // 准备工作终于做完，现在来用子进程执行吧
      
      



      pid_t ret = fork();
      if(ret == 0)
      {
         execvp(CommandExec[0],CommandExec);
         exit(-1);
      }

      pid_t isSuccess = waitpid(ret , NULL , 0);
      if(isSuccess == ret)
      {
         printf("执行完毕\n");
      }

   }
   return 0;
}
